require('module-alias/register');
const Koa = require('koa');
const http = require('http');
const utils = require('@/src/server/libs/Utils');
const router = require('@/src/middlewares/routes')
const SystemLog = require('@/src/server/libs/SysLog/SystemLog');
const init = require('@/src/bootup/init');
const session = require('koa-session');
const bodyParser = require('@/src/middlewares/bodyParser');
const koaLog = require('@/src/middlewares/koaLog');

const sessionConfig = {
    key: 'koa:sess',
    maxAge: 'session',
    overwrite: true,
    httpOnly: true,
    signed: true,
    rolling: false
};
async function createServer(port) {
    const app = new Koa();
    const httpServer = http.createServer(app.callback());
    app.use(session(sessionConfig, app))
        .use(koaLog)
        .use(bodyParser)
        .use(router.routes(), router.allowedMethods())
        .on('error', SystemLog)
    httpServer.listen(port, () => {
        console.log(`Server running on port ${port}`);
        init(httpServer); // 调用初始化函数并传入 httpServer
    });
}
async function listen(port) {
    let address = utils.getIPAddress();
    console.log(`  App running at:\n`, ` - Local:   http://localhost:${port}\n`, ` - Network: http://${address}:${port} `);
    await createServer(port);
}

exports.listen = listen;